import IdbKvStore from "idb-kv-store";
import {add} from 'lodash-es'

const CACHE_KEYS = {
  CITIES: '_CITIES',
  TOTAL: '_TOTAL'
}

const config = {
  dbName: 'DataFilling',
  version: 1
}

const indexDBCache = {
  set(key, value) {
    const store = new IdbKvStore(config.dbName)
    store.set(key, value)
  },

  async get(key) {
    const store = new IdbKvStore(config.dbName)
    return await store.get(key)
  },

  remove(key) {
    const store = new IdbKvStore(config.dbName)
    store.remove(key)
  },

  async setTotal(rows) {
    //缓存城市名称
    const names = rows.map(x => x.name)
    const cities = await this.get(CACHE_KEYS.CITIES)
    if (!cities) {
      this.set(CACHE_KEYS.CITIES, names)
    } else {
      this.set(CACHE_KEYS.CITIES, Array.from(new Set([...cities, ...names])))
    }

    //更新合计
    let totalArr = await this.get(CACHE_KEYS.TOTAL)
    if (!totalArr) {
      totalArr = rows
    } else {
      totalArr.forEach(item => {
        const row = rows.find(x => x.name === item.name)
        if (row) {
          item.value = add(item.value, row.value)
        }
      })
    }
    this.set(CACHE_KEYS.TOTAL, totalArr.map(item => ({name: item.name, value: item.value})))
  }
}

export default indexDBCache

export {CACHE_KEYS}